// pages/search/search.js
Page({

  data: {
    list:[],
    keyword:'',
    historyList:[]
  },

  onLoad: function (options) {
    // 一开始要读取本地存储的历史搜索内容
    if(wx.getStorageSync('history')){
      this.setData({
        historyList:wx.getStorageSync('history')
      })
    }
  },

  // 处理关键词输入
  handleInput(e){
    // console.log(e)
    const keyword = e.detail.value;
    this.setData({
      keyword
    });
  },

  // 点击确认搜索
  handleConfirm(){
    // 将搜索过的关键词存到本地存储里
    console.log('确认搜索')
    let {keyword} = this.data
    if(keyword===""){
      wx.showLoading({
        title:"关键词不能为空!",
        mask: true,
        success: (result) => {
          wx.hideLoading();
        },
      });
      return;
    }
    wx.showLoading({
      title: "数据加载中",
      mask: true,
    });
      
    let historyList = wx.getStorageSync('history');
    if(historyList.length === 0){
      wx.setStorageSync('history', [keyword]);
      this.setData({
        historyList:[keyword]
      })
    }else{
      // 判断是否有重复的关键词，如果有，则进行更新
      const index = historyList.findIndex(item=>item === keyword);
      if(index===-1){
        // 不存在，则插入
        historyList.unshift(keyword);
        wx.setStorageSync('history', historyList);
      }else{
        // 存在，则删掉再更新
        historyList.splice(index,1);
        historyList.unshift(keyword);
        wx.setStorageSync('history', historyList);
      }

      this.setData({
        historyList
      })
    }
    this.handleSearch(keyword);
  },

  // 删除搜索记录
  handleDelete(){
    const that = this;
    wx.showModal({
      title: '提示',
      content: '是否删除搜索记录',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: (result) => {
        if (result.confirm) {
          wx.removeStorageSync('history');
          that.setData({
            historyList:[]
          })
        }
      },
    });
      
  },

  // 点击关键词，则进行搜索
  touchKeyword(e){
    console.log('点击关键词',e);
    this.setData({
      keyword:e.currentTarget.id
    });
    this.handleSearch(e.currentTarget.id);
  },


  // 关键词搜索得到匹配数据
  handleSearch(keyword){
    const that = this;
    wx.cloud.callFunction({
      name:'handleSearchKeyword',
      data:{
        keyword
      },
      success:res=>{
        console.log('匹配关键词结果',res);
        that.setData({
          list:res.result.data
        })
        wx.hideLoading()
      }
    })
  },


  // 跳转到活动详情页
  gotoDetail(e){
    console.log('跳转到活动详情页',e.currentTarget.id);
    wx.navigateTo({
      url: `/pages/detail/detail?id=${e.currentTarget.id}`
    });
  },

})